package com.pitb.citizenreporting;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.pitb.citizenreporting.db.HakathonDb;

public class ReportProblem extends Activity implements OnClickListener {
	ProgressDialog progressDialog;
	EditText mProblem, mSteetAddress, mContact;
	Spinner mProvince, mCity, mArea, mType;
	String[] city;
	String[] area;
//	private MapView mapView;
//	private MapController myMapController;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.report_problem);
		mProblem = (EditText) findViewById(R.id.problem);
		mSteetAddress = (EditText) findViewById(R.id.address);
		mContact = (EditText) findViewById(R.id.contact);
		mProvince = (Spinner) findViewById(R.id.provance);
		mCity = (Spinner) findViewById(R.id.city);
		mArea = (Spinner) findViewById(R.id.area);
		mType = (Spinner) findViewById(R.id.complaint_type);
//		mapView = (MapView) findViewById(R.id.mapview);
//		myMapController = mapView.getController();
//		mapView.setBuiltInZoomControls(true);
		mSteetAddress.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				String address = s.toString()
						+ mArea.getSelectedItem().toString()
						+ mCity.getSelectedItem().toString()
						+ mProvince.getSelectedItem().toString();
//				showMap(address);
			}
		});
		ImageButton submit = (ImageButton) findViewById(R.id.submit);
		ImageButton cancel = (ImageButton) findViewById(R.id.cancel);
		submit.setOnClickListener(this);
		cancel.setOnClickListener(this);
		city = getArray(R.array.cit_pun);
		area = getArray(R.array.area_lhr);
		bindSpinnerCity(city);
		bindArea(area);
		bindType();
		mProvince.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {				
				bindSpinnerCity(city);
				bindArea(area);
				String address = mSteetAddress.getText().toString()
						+ mArea.getSelectedItem().toString()
						+ mCity.getSelectedItem().toString()
						+ mProvince.getSelectedItem().toString();
//				showMap(address);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		mCity.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {								
				String address = mSteetAddress.getText().toString()
						+ mArea.getSelectedItem().toString()
						+ mCity.getSelectedItem().toString()
						+ mProvince.getSelectedItem().toString();
//				showMap(address);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});
		String address = mSteetAddress.getText().toString() + mCity.getSelectedItem().toString()
							+ mProvince.getSelectedItem().toString();
//		showMap(address);
//		mProvince.setSelection(5);
//		mArea.setSelection(4);
	}

	void bindSpinnerCity(String[] city) {
		ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, city);
		cityAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mCity.setAdapter(cityAdapter);

	}
	
	String[] getArray(int arg){
		return getResources().getStringArray(arg);
	}

	void bindArea(String[] area) {
		ArrayAdapter<String> areaAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, area);
		areaAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mArea.setAdapter(areaAdapter);
	}

	void bindType() {
		ArrayAdapter<String> areaAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,getResources().getStringArray(R.array.complaint_type));
		areaAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mType.setAdapter(areaAdapter);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.cancel) {
			finish();
		} else if (v.getId() == R.id.submit) {
			String problem = mProblem.getText().toString();
			String address = mSteetAddress.getText().toString();
			String contact = mContact.getText().toString();
			String province = mProvince.getSelectedItem().toString();
			String city = mCity.getSelectedItem().toString();
			String area = mArea.getSelectedItem().toString();
			String type = mType.getSelectedItem().toString();
			if (TextUtils.isEmpty(problem)) {
				Toast.makeText(getApplicationContext(), "Enter Your Problem!",
						0).show();
				return;
			}
			if (TextUtils.isEmpty(address)) {
				Toast.makeText(getApplicationContext(), "Enter Address!", 0)
						.show();
				return;
			}

			if (contact == null) {
				contact = "";
			}
			showDialog();
			PostTask task = new PostTask(contact, address, problem, province,
					city, area, type);
			task.start();
		}
	}

	class PostTask extends Thread {
		String number;
		String address;
		String problem;
		String province;
		String city;
		String area;
		String type;

		public PostTask(String numberarg, String addressarg, String problemarg,
				String provincearg, String cityarg, String areaarg,
				String typearg) {
			number = numberarg;
			address = addressarg;
			problem = problemarg;
			province = provincearg;
			city = cityarg;
			area = areaarg;
			type = typearg;
		}

		@Override
		public void run() {
			String response = HttpPostUtil.postComplaint(problem, address,
					number, province, city, area, type);
			Log.i("Citizen Reporting", "Server response is \n" + response);
			if (TextUtils.isEmpty(response)) {
				Message msg = mHandler.obtainMessage(0);
				Bundle b = new Bundle();
				b.putString("msg", "Unable to communicate with server!");
				msg.setData(b);
				mHandler.sendMessage(msg);
				return;
			}
			JsonParser parse = JsonParser.parse(response);
			if (parse != null) {
				if (parse.status.equals(JsonParser.ERROR)) {
					Message msg = mHandler.obtainMessage(0);
					Bundle b = new Bundle();
					b.putString("msg", parse.message);
					msg.setData(b);
					mHandler.sendMessage(msg);
					return;
				}
				if (parse.status.equals(JsonParser.SUCCESS)) {
					HakathonDb db = new HakathonDb();
					db.insertCompalint(number, address, problem, province,
							city, area, type, "In-queue", parse.complaintId);
					Message msg = mHandler.obtainMessage(0);
					Bundle b = new Bundle();
					b.putString("msg",
							"Successfully submitted compalint, You complaint id is "
									+ parse.complaintId);
					msg.setData(b);
					mHandler.sendMessage(msg);
					return;
				}
			}
			mHandler.sendEmptyMessage(1);
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				dismiss();
				String command = msg.getData().getString("msg");
				Toast.makeText(getApplicationContext(), command, 0).show();
				break;
			case 1:
				dismiss();
				break;
			}
		}
	};

	static class JsonParser {
		public static final String STATUS = "status";
		public static final String COMPLAINT_ID = "complaint-ID";
		public static final String MESSAGE = "message";

		public static final String ERROR = "Error";
		public static final String SUCCESS = "Success";

		String status;
		String message;
		String complaintId;

		public static JsonParser parse(String response) {
			try {
				JSONObject json = new JSONObject(response);
				JsonParser parse = new JsonParser();
				parse.status = json.getString(STATUS);
				parse.message = json.getString(MESSAGE);
				parse.complaintId = json.getString(COMPLAINT_ID);
				return parse;
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	private void showDialog() {
		progressDialog = ProgressDialog.show(this, "",
				"Submitting. Please wait...", true);
	}

	void dismiss() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	@Override
	protected void onPause() {
		dismiss();
		super.onPause();
	}

//	@Override
//	protected boolean isRouteDisplayed() {
//		// TODO Auto-generated method stub
//		return false;
//	}
//	
//	class InterestingLocations extends ItemizedOverlay<OverlayItem> {
//
//		private List<OverlayItem> locations = new ArrayList<OverlayItem>();
//		private Drawable marker;
//
//		public InterestingLocations(Drawable defaultMarker, GeoPoint myPlace) {
//			super(defaultMarker);
//			// TODO Auto-generated constructor stub
//			this.marker = defaultMarker;
//			// create locations of interest			
//			locations.add(new OverlayItem(myPlace, "My Place", "My Place"));
//			populate();
//		}
//
//		@Override
//		protected OverlayItem createItem(int i) {
//			// TODO Auto-generated method stub
//			return locations.get(i);
//		}
//
//		@Override
//		public int size() {
//			// TODO Auto-generated method stub
//			return locations.size();
//		}
//
//		@Override
//		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
//			// TODO Auto-generated method stub
//			super.draw(canvas, mapView, shadow);
//
//			boundCenterBottom(marker);
//		}
//	}
	
//	public void findAddress(final String address){
//		Thread t = new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
//				showMap(address);
//				
//			}
//		});t.start();
//	}
//	
//	void showMap(String address){		
//		String output = LocationUtil.getLocation(address);
//        Log.i("Google Service", output);   
//        UserLocation googleServices = UserLocation.getUserLocation(output);
//		if(googleServices != null ){
//			Bundle b = new Bundle();
//			b.putDouble("lat", googleServices.latitude);
//			b.putDouble("lng", googleServices.longitude);
//			Message message = handler.obtainMessage();
//			message.setData(b);
//			handler.sendMessage(message);
//		}		
//	}
	
//	Handler handler = new Handler(){
//		public void handleMessage(Message msg) {
//			double lat = getIntent().getDoubleExtra("lat", 0);
//			double lng = getIntent().getDoubleExtra("lng", 0);
//			GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
//
//			myMapController.animateTo(point);
//			mapView.getController().setZoom(16);
//
//			Drawable marker = getResources().getDrawable(
//					android.R.drawable.ic_menu_myplaces);
//			marker.setBounds(0, 0, marker.getIntrinsicWidth(),
//					marker.getIntrinsicHeight());
//			mapView.getOverlays().add(new InterestingLocations(marker, point));
//		}
//	};

}
